<!--
 * @Autor: chaotang.zhang
 * @Date: 2020-08-12 15:55:31
 * @LastEditors: chaotang.zhang
 * @LastEditTime: 2020-08-14 18:31:38
-->
<template>
  <div class="sku">
    <el-form label-position="left" label-width="100px" size="mini" :model="formData">
      <!-- <el-form-item label="属性类型：">
        <el-select v-model="formData.type">
          <el-option
            v-for="(item) in selectData"
            :label="item.title"
            :key="item.id"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item> -->

      <el-form-item label="商品规格:">
        <div class="sku--maini">
          <div class="sku--specification">
            <div
              class="sku--specification--row"
              v-for="(item, index) in formData.specification"
              :key="index"
            >
              <div class="sku--specification--label">{{item.title}}：</div>
              <el-row class="sku--specification--main">
                <div class="sku--specification--item">
                  <el-checkbox-group
                    v-model="formData.specification[index].checked"
                    :ref="item.key"
                    @change="checkboxChange({refName:item.key, index})"
                  >
                    <el-checkbox
                      v-for="value in item.values"
                      :label="value"
                      :key="value"
                    ></el-checkbox>
                  </el-checkbox-group>
                </div>
                <div
                  :span="1"
                  class="sku--specification--delete--btn"
                  v-if="addSpecificationList[index].flag"
                >
                  <el-button
                    type="text"
                    size="small"
                    class="el-icon-delete"
                    @click="removeSpecification({refName:item.key, index})"
                  >删除</el-button>
                </div>
                <el-row :gutter="20" type>
                  <el-col :span="3">
                    <el-input v-model.trim="addSpecificationList[index].value"></el-input>
                  </el-col>
                  <el-col :span="1">
                    <el-button @click="addSpecification(index)">添加</el-button>
                  </el-col>
                </el-row>
              </el-row>
            </div>
          </div>

          <div class="specification--table--box">
            <el-table :data="allSkuData">
              <el-table-column
                v-for="item in myTableData"
                :key="item.title"
                :label="item.title"
                :prop="item.key"
              ></el-table-column>
              <el-table-column :label="$t('sku.price')">
                <template slot-scope="scope">
                  <el-input-number controls-position="right" :step="0.1" v-model="scope.row.price"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column :label="$t('sku.gcount')">
                <template slot-scope="scope">
                 <el-input v-model="scope.row.gcount"></el-input>
                </template>
              </el-table-column>
              <el-table-column :label="$t('sku.InventoryWarningValue')">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.InventoryWarningValue"></el-input>
                </template>
              </el-table-column>
              <el-table-column :label="$t('sku.skuCode')">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.skuCode"></el-input>
                </template>
              </el-table-column>
              <el-table-column :label="$t('action')">
                <template slot-scope="scope">
                  <el-button
                    calss="delete-btn"
                    type="text"
                    icon="el-icon-delete"
                    @click="deleteSkuItem(scope.$index)"
                  >{{$t('delete')}}</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="specification--table--btns">
            <el-button type="primary" @click="getSkuData">刷新列表</el-button>
            <el-button
              type="primary"
              @click="addspecificationTypeVisible = !addspecificationTypeVisible"
            >{{addspecificationTypeVisible?'关闭':'添加规格'}}</el-button>
          </div>
          <el-row v-if="addspecificationTypeVisible">
            <el-row class="sku--addspecificationType--row">
              <el-col :span="2">规格名称：</el-col>
              <el-col :span="6">
                <el-input v-model="addspecificationTypeValue"></el-input>
              </el-col>
            </el-row>
            <el-row class="sku--addspecificationType--row">
              <el-col :span="2">规格key：</el-col>
              <el-col :span="6">
                <el-input v-model="addspecificationTypeKey"></el-input>
              </el-col>
            </el-row>
            <!-- 可选值添加 -->
            <el-row class="sku--specification--addoption">
              <el-col :span="2">添加可选值：</el-col>
              <el-col :span="22">
                <el-tag
                  :key="tag"
                  v-for="tag in dynamicTags"
                  class="sku--specification--newsoption--tag"
                  closable
                  size="miin"
                  :disable-transitions="false"
                  @close="handleClose(tag)"
                >{{tag}}</el-tag>
                <el-input
                  class="sku--specification--newsoption--input"
                  v-if="inputVisible"
                  v-model="inputValue"
                  ref="saveTagInput"
                  @keyup.enter.native="handleInputConfirm"
                  @blur="handleInputConfirm"
                ></el-input>
                <el-button
                  @click="showInput"
                  v-else
                  class="sku--specification--newsoption--btn"
                >+ New Option</el-button>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="2">
                <el-button class="add-btn" icon="el-icon-add" @click="addspecificationType">添加</el-button>
              </el-col>
            </el-row>
          </el-row>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'sku',
  data () {
    return {
      formData: {
        type: '',
        specification: [
          {
            title: '颜色',
            key: 'color',
            values: ['红色', '白色'],
            checked: []
          },
          {
            title: '内存',
            key: 'capacity',
            values: ['32G', '64G'],
            checked: []
          }
        ]
      },
      selectData: [
        {
          id: 1,
          title: '手机数码'
        },
        {
          id: 2,
          title: '冷链生鲜'
        },
        {
          id: 3,
          title: '衣服时装'
        }
      ],
      // 要在表格渲染的数据
      myTableData: [],
      // 根据规格类型生成的笛卡尔积数据
      DescartesData: [],
      // 对笛卡尔积进行转化为符合表格类型的数据
      allSkuData: [],
      // 添加规格选项
      addSpecificationList: [],
      // 添加规格类型
      addspecificationTypeValue: '',
      addspecificationTypeKey: '',
      // 控制添加规格类型输入框是否显示变量
      addspecificationTypeVisible: false,
      // 添加规格可选数据
      dynamicTags: [],
      // 控制input显示
      inputVisible: false,
      // input输入值
      inputValue: '',
      // sku要生成的key
      newskey: ''
    }
  },
  created () {
    this.init()
  },
  methods: {
    // 把商品规格按照笛卡尔积生成
    getDescartesData ({ skuarr = [], i = 0, list }) {
      for (let j = 0; j < list[i].checked.length; j++) {
        if (i < list.length - 1) {
          skuarr[i] = list[i].checked[j]
          this.getDescartesData({ skuarr, i: i + 1, list })
        } else {
          // 拓展运算符合并数组
          this.DescartesData.push([...skuarr, list[i].checked[j]])
        }
      }
    },
    // 把生成的笛卡尔积数据转化为一维数组（表格渲染类型）
    conversion () {
      const arr = []
      this.DescartesData.forEach((el) => {
        const newSKU = {}
        this.newskey = ''
        el.forEach((value, index) => {
          this.newskey += `${value} `
          newSKU[this.myTableData[index].key] = value
        })

        newSKU.key = this.newskey.trim().split(' ').join('-')
        newSKU.attributeTypes = ''
        newSKU.specificationOfGoods = ''
        newSKU.price = 0
        newSKU.InventoryWarningValue = ''
        newSKU.skuCode = ''
        arr.push(newSKU)
      })
      this.coincide(arr)
    },
    // 判断新数据和老数据重合，重合就不改变
    coincide (arr) {
      arr.forEach((el, index) => {
        const position = this.allSkuData.findIndex(item => el.key === item.key)
        if (position !== -1) {
          arr[index] = this.allSkuData[position]
        }
      })
      this.allSkuData = arr
    },
    // 获取SKU表格数据方法
    getSkuData () {
      this.DescartesData = []
      const list = []
      this.formData.specification.forEach(item => {
        if (item.checked.length > 0) {
          list.push(item)
        }
      })

      if (list.length === 0) {
        return this.$notify({
          title: '提示',
          message: this.$createElement('i', '请勾选规格')
        })
      }

      this.myTableData = list

      this.getDescartesData({ list: list })
      this.conversion()
    },
    // 勾选发生改变
    checkboxChange ({ refName, index }) {
      // 获取当前选中的值
      const target = this.$refs[refName][0]
      const checkValues = this.$_.cloneDeep(target.value)

      // 判断 删除按钮是否展示
      this.addSpecificationList[index].flag = false
      if (checkValues.length > 0) {
        this.addSpecificationList[index].flag = true
      }
    },
    // 添加规格方法
    addSpecification (index) {
      if (this.addSpecificationList[index].value.length === 0) return false
      const specificationList = this.formData.specification[index].values
      specificationList.push(this.addSpecificationList[index].value)
      this.addSpecificationList[index].value = ''
    },
    // 删除选择规格
    removeSpecification ({ refName, index }) {
      // 获取当前选中的值
      const target = this.$refs[refName][0]
      const checkValues = this.$_.cloneDeep(target.value)
      if (checkValues && checkValues.length === 0) return
      // 然后获取它们的位置逐个删除
      const specificationList = this.formData.specification[index].values
      const checkedList = this.formData.specification[index].checked
      checkValues.forEach((el) => {
        const position = specificationList.findIndex((item) => item === el)
        if (position !== -1) {
          if (specificationList.length === 1) {
            return this.$notify({
              title: '提示',
              message: this.$createElement('i', '规格中必须含有一个可选值')
            })
          }
          specificationList.splice(position, 1)
        }
        const checkPosition = checkedList.findIndex((item) => item === el)
        if (checkPosition !== -1) {
          checkedList.splice(checkPosition, 1)
        }
      })
    },
    // 删除生成的SKU的某一项
    deleteSkuItem (index) {
      this.allSkuData.splice(index, 1)
    },
    // 添加规格类型
    addspecificationType () {
      if (this.addspecificationTypeValue.length === 0) {
        return this.$notify({
          title: '提示',
          message: this.$createElement('i', '添加规格类型不能为空')
        })
      }

      if (this.addspecificationTypeKey.length === 0) {
        return this.$notify({
          title: '提示',
          message: this.$createElement('i', '添加规格类型KEY不能为空')
        })
      }

      if (this.dynamicTags.length === 0) {
        return this.$notify({
          title: '提示',
          message: this.$createElement('i', '添加规格类型可选值不能为空')
        })
      }

      const data = {
        title: this.addspecificationTypeValue,
        key: this.addspecificationTypeKey,
        values: this.dynamicTags,
        checked: []
      }
      // 更新规格数据
      this.undateSpecification()
      this.formData.specification.push(data)

      this.addspecificationTypeVisible = false
      this.addspecificationTypeValue = ''
      this.dynamicTags = []
    },
    // 更新规格数据
    undateSpecification (position) {
      // 更新添加可选值
      this.addSpecificationList.push({
        value: '',
        flag: false
      })
    },
    init () {
      this.formData.specification.forEach(() => {
        this.undateSpecification()
      })
    },
    // 取消要添加的规格可选值
    handleClose (tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
    },
    // 显示添加规格可选值的输入框
    showInput () {
      this.inputVisible = true
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 添加规格可选值的输入框输入框完成后的动作
    handleInputConfirm () {
      const inputValue = this.inputValue
      if (inputValue) {
        this.dynamicTags.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    }
  }
}
</script>

<style lang="scss" scoped>
.sku {
  .sku--specification {
    padding: 30px;
    background-color: #f8f9fd;
  }
  .sku--specification--main {
    padding: 0 16px;
  }
  .specification--table--box {
    margin-top: 16px;
  }
  .specification--table--btns {
    margin: 16px 0;
  }
  .sku--specification--delete--btn {
    margin-left: 10px;
    display: inline-block;
    vertical-align: sub;
  }
  .sku--specification--row {
    margin-top: 10px;
  }
  .sku--specification--item {
    display: inline-block;
    padding: 10px 0;
  }
  .sku--specification--addoption {
    margin: 10px 0 10px 0;
  }
  .sku--addspecificationType--row {
    margin-top: 10px;
  }
  .sku--specification--newsoption--tag {
    margin: 0 4px;
  }
  .sku--specification--newsoption--input {
    min-width: 60px;
    max-width: 100px;
  }
}
</style>
